﻿using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;

namespace Server.Utils
{
    public class JwtUtil
    {
        public static string GetToken(string memberId)
        {
            var jwtConfig = new Server.Utils.ConfigurationUtil().GetAppSettings<Server.Entities.Appsettings.JwtConfig>("JWT");
            var claims = new[] {
                 new Claim(ClaimTypes.Name,"JWT"),
                new Claim("memberId",memberId),
                new Claim("expires",DateTime.UtcNow.AddDays(jwtConfig.Expires).ToString()),
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.Key));

            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
               issuer: jwtConfig.Issuer,
                claims: claims,
                expires: DateTime.UtcNow.AddDays(jwtConfig.Expires),
                signingCredentials: credentials);

            return "Bearer " + new JwtSecurityTokenHandler().WriteToken(token);
        }

        public static string GetMemberIdFromToken(string token = null)
        {
            if (string.IsNullOrEmpty(token))
                return default;
            try
            {
                string tokenStr = token.Replace("Bearer ", "");
                var handler = new JwtSecurityTokenHandler();
                var payload = handler.ReadJwtToken(tokenStr).Payload;
                var claims = payload.Claims;
                return claims.First(claim => claim.Type == "memberId")?.Value;
            }
            catch (Exception)
            {

                return null;
            }

        }

        public static DateTime GetEexpires(string token = null)
        {
            if (string.IsNullOrEmpty(token))
                return default;
            try
            {
                string tokenStr = token.Replace("Bearer ", "");
                var handler = new JwtSecurityTokenHandler();
                var payload = handler.ReadJwtToken(tokenStr).Payload;
                var claims = payload.Claims;
                return DateTime.Parse(claims.First(claim => claim.Type == "expires")?.Value);
            }
            catch (Exception)
            {

                return default;
            }

        }

        /// <summary>
        /// 检查过期
        /// </summary>
        /// <returns></returns>
        public static string CheckOverdue(string token)
        {
            DateTime dt = JwtUtil.GetEexpires(token);
            if (dt != default)
            {
                if (dt.CompareTo(DateTime.Now) <= 0)
                {
                    return null;
                }
                if (dt.CompareTo(DateTime.Now.AddDays(-5)) >= 0)
                {
                    return JwtUtil.GetToken(JwtUtil.GetMemberIdFromToken(token));
                }

            }
            return null;
        }
    }
}
